import re
import datetime
from mongoengine import StringField, DateTimeField, ListField, IntField, \
    URLField, BooleanField, DictField, ReferenceField
from app.database import BASE_DB
from utils.mongoengine import DataDocument as Document


class Permission(Document):
    _model_desc_ = 'permission'
    id = StringField(verbose_name='权限值', help_text='冗余字段，格式为content-action，用于唯一鉴别和搜索permission', primary_key=True)
    content = StringField()
    action = StringField()
    name = StringField(verbose_name='权限展示名称')
    vname = StringField(verbose_name='权限全名')
    desc = StringField(verbose_name='描述')
    is_deleted = BooleanField(required=False)
    delete_time = DateTimeField()
    module = StringField(verbose_name='模块名')
    autosync = BooleanField(required=False)
    meta = {'strict': True, 'db_alias': BASE_DB}

    pattern = re.compile("(?P<content>((\w)*(\.)?(\w)*)+),(?P<action>(\w)*)(,)?(?P<module>(\w)*)(,)?(?P<name>(\w)*)(,)?(?P<vname>((\w)*(\.)?(\w)*)+)(,)?(?P<desc>([ \w\(\)])*)")

    def __str__(self):
        return "%s-%s" % (self.content, self.action)

    def to_line(self, skip_comma=True):
        res = [self.content, self.action, self.module, self.name, self.vname, self.desc]
        if skip_comma:
            return ','.join([i for i in res if i])
        return ','.join([i if i else '' for i in res])

    def set_deleted(self):
        self.is_deleted = True
        self.delete_time = datetime.datetime.utcnow()
        self.save()

    @staticmethod
    def parse_line(line, raise_except=True):
        res = Permission.pattern.match(line)
        if res:
            res.groupdict()["id"] = res.groupdict()["content"] + "-" + res.groupdict()["action"]
            return Permission(**res.groupdict())
        else:
            if raise_except:
                raise Exception("can not parse line to permission: %s" % str(line))

    @staticmethod
    def output_all():
        for p in Permission.objects.all():
            print(p.to_line())
        return

    def save(self, **kwargs):
        if not self.id:
            self.id = '%s-%s' % (self.content, self.action)
        return super(Permission, self).save(**kwargs)

    def set_deleted(self):
        Permission.objects(id=self.id).delete()
